package com.example.demo.controller;

import com.example.demo.pojo.Journal;
import com.example.demo.pojo.User;
import com.example.demo.service.JournalService;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtil;  // 引入 JwtUtil
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.example.demo.util.Md5Util.StringInMd5;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService; // 服务层，负责处理业务逻辑

    @Autowired
    private JournalService journalService;



    private String[] userTypeList = {"超级管理员", "管理员", "人员"};

    // 登录接口
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        // 查找用户
        User user = userService.findByUsername(username);

        if (user == null) {
            return ResponseEntity.status(401).body("Invalid username or password.");
        } else {
            // 将密码使用 MD5 加密
            String md5Password = StringInMd5(password);

            if (md5Password.equals(user.getPassword())) {
                // 根据用户类型查找状态
                int type = user.getType();
                int status = userService.findByName(userTypeList[type]);

                if (status == 1) {
                    // 登录成功，生成 JWT Token
                    String token = JwtUtil.genToken(user);
                    Map<String, Object> response = new HashMap<>();
                    response.put("token", token);
                    response.put("username", username);
                    response.put("type", type);

                    Journal journal = new Journal();
                    // 设置日志
                    journal.setOperator(username);
                    journal.setColor(1);
                    journal.setType("登录系统");
                    journal.setOperatorId(String.valueOf(user.getId()));
                    journalService.insert(journal);
                    // 返回包含 JWT Token 的响应
                    return ResponseEntity.ok(response);
                } else {
                    return ResponseEntity.status(402).body("User status is inactive.");
                }
            } else {
                return ResponseEntity.status(401).body("Invalid username or password.");
            }
        }
    }
}
